﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Net.Mail;
using System.Net;
using System.IO;


namespace IBS2RPO
{
    public partial class Service1 : ServiceBase
    {

        private Timer timer = null;

        public Service1()
        {
            InitializeComponent();

            try
            {
                if (!EventLog.SourceExists(this.ServiceName + "_log"))
                    EventLog.CreateEventSource(this.ServiceName, this.ServiceName + "_log");
            }
            catch { }

            serviceLog.Source = this.ServiceName + "_log";
            serviceLog.Log = this.ServiceName + "_log";

        }

        protected override void OnStart(string[] args)
        {
            serviceLog.WriteEntry(this.ServiceName + " запущен");

            Properties.Settings.Default.Reload();

            var ExecuteTimes = Properties.Settings.Default.ExecuteTimes;

            if (Properties.Settings.Default.ExecuteImmediately)
                ExecuteTimes.Add(DateTime.Now.AddMinutes(1).ToString("HH:mm"));

            timer = new Timer();
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = TimerUtil.GetNewTimerInterval(ExecuteTimes);
            timer.Enabled = true;
        }

        protected override void OnStop()
        {
            serviceLog.WriteEntry(this.ServiceName + " остановлен");

            timer.Stop();
            timer.Close();
        }

        /// <summary>
        /// При срабатывании таймера
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            // Останавливаем таймей и стартуем выполнение выгрузки
            timer.Stop();

            Process();

            // Интервал таймера
            Properties.Settings.Default.Reload();
            timer.Interval = TimerUtil.GetNewTimerInterval(Properties.Settings.Default.ExecuteTimes);
            timer.Start();
        }

        private void Process()
        {
            try
            {
                var path = Properties.Settings.Default.Path2Save;

                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);

                var IbsConnectionString = Properties.Settings.Default.IBSConnectionString;

                var ibs = new IBS.IbsDataContext(IbsConnectionString);

                DateTime tstDate = Properties.Settings.Default.LastDate;

                var SaleOrderList = ibs.GetSaleOrdersTNK();

                foreach (var saleOrder in SaleOrderList)
                {
                    try
                    {
                        var RPO_data = ibs.GetRPO(saleOrder.INVOICE_ID);
                        foreach (var line in RPO_data)
                        {
                            if (!Directory.Exists(path + @"\" + line.IP))
                                Directory.CreateDirectory(path + @"\" + line.IP);
                            line.SerializeToFile(path + @"\" + line.IP + @"\RPO_Invoice_" + line.LOCATION_KEY + "_" + line.SUPPLIERCODE + "_" + line.INVOICECODE + "_" + line.INVOICEDATE.ToString("ddMMyyyy") + ".1");
                        }
                        ibs.UpdateStatus(saleOrder.INVOICE_ID);
                    }
                    catch (Exception ex)
                    {
                        
                    }

                }
            }
            catch (Exception ex)
            {
                

            }
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="to"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        private void SendEMail(string to, string subject, string body)
        {
            string smtpServer = Properties.Settings.Default.SMTP_SERVER_HOST_1;
            int smtpServerPort = Properties.Settings.Default.SMTP_SERVER_PORT;
            string smtpServerFrom = Properties.Settings.Default.ServiceMailAddress;
            try
            {
                SmtpClient client = new SmtpClient(smtpServer, smtpServerPort);
                client.UseDefaultCredentials = true;

                MailMessage mailNew = new MailMessage();

                mailNew.From = new MailAddress(smtpServerFrom);

                if (to != null)
                    to.Split(new char[] { ';', ',', ' ' }).ToList().ForEach(r =>
                    {
                        if (r.Length != 0)
                            mailNew.To.Add(new MailAddress(r));
                    });

                mailNew.Subject = subject;
                mailNew.Body = "<HTML><HEAD><BODY><p>" + body + "</p></BODY></HTML>";
                mailNew.BodyEncoding = System.Text.Encoding.UTF8;
                mailNew.SubjectEncoding = System.Text.Encoding.UTF8;
                mailNew.IsBodyHtml = true;
                client.Send(mailNew);
            }
            catch (Exception ex)
            {
                serviceLog.WriteEntry("ERROR: Send e-mail " + ex.Message, System.Diagnostics.EventLogEntryType.Error, 16);
            }
        }
    }
}
